package com.test.ad.demo.util;

import android.app.Activity;
import android.content.Context;

import java.util.ArrayList;
import java.util.List;

public class ActivityManager {
    private static ActivityManager instance;
    private List<Activity> activityList;

    private ActivityManager() {
        activityList = new ArrayList<>();
    }

    public static ActivityManager getInstance() {
        if (instance == null) {
            synchronized (ActivityManager.class) {
                if (instance == null) {
                    instance = new ActivityManager();
                }
            }
        }
        return instance;
    }

    /**
     * 添加 Activity 到管理列表
     */
    public void addActivity(Activity activity) {
        if (activityList == null) {
            activityList = new ArrayList<>();
        }
        activityList.add(activity);
    }

    /**
     * 从管理列表移除 Activity
     */
    public void removeActivity(Activity activity) {
        if (activityList != null) {
            activityList.remove(activity);
        }
    }

    /**
     * 结束所有 Activity
     */
    public void finishAllActivities() {
        if (activityList != null) {
            for (Activity activity : activityList) {
                if (activity != null && !activity.isFinishing()) {
                    activity.finish();
                }
            }
            activityList.clear();
        }
    }

    /**
     * 完全退出应用程序
     */
    public void exitApp(Context context) {
        try {
            // 结束所有 Activity
            finishAllActivities();

            // 杀死进程
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(0);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取当前 Activity 数量
     */
    public int getActivityCount() {
        return activityList != null ? activityList.size() : 0;
    }
}